package com.li.o2oSystem.util.weixin;

import java.security.MessageDigest;
import java.util.Arrays;

/**
 * 微信请求校验工具
 * @author Administrator
 */
public class SignUtil {
	//设置token,要与微信设置的一致
	private static String token="o2oSystem";
	/**
	 * 验证签名
	 * @param signature
	 * @param timestamp
	 * @param nonce
	 * @return
	 */
	public static boolean checkSignature(String signature,String timestamp,String nonce){
		//将三个参数进行字典排序
		String [] arr = new String[] {token,timestamp,nonce};
		Arrays.sort(arr);
		StringBuilder content = new StringBuilder();
		for (int i = 0; i < arr.length; i++) {
			content.append(arr[i]);			
		}
		MessageDigest md = null;
		String tmpStr = null;
		try{
			md = MessageDigest.getInstance("SHA-1");
			//将三个字符串拼接成一个字符串，进行sha1加密
			byte [] digest = md.digest(content.toString().getBytes());
			tmpStr = byteToStr(digest);
		}catch(Exception e){
			e.printStackTrace();
		}
		content = null;
		//将sha1加密后的字符串与signatured对比，并返回
		return tmpStr != null ? tmpStr.equals(signature.toUpperCase()):false;
	}
	/**
	 * 将字节数组转换为16进制字符串
	 * @param digest
	 * @return
	 */
	private static String byteToStr(byte[] digest) {
		String strDigest = "";
		for (int i = 0; i < digest.length; i++) {
			strDigest += byteToHexStr(digest[i]);
			
		}
		return strDigest;
	}
	/**
	 * 将字节转换为16进制字符串
	 * @param b
	 * @return
	 */
	private static String byteToHexStr(byte b) {
		char[] Digit = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
		char[] tempArr = new char[2];
		tempArr[0] = Digit[(b >>> 4 ) & 0x0F];
		tempArr[1] = Digit[b & 0x0F];
		
		String s = new String(tempArr);
		return s;
	}
}
